package stone926.mods.more_enchantments.effect;

import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.attribute.AttributeContainer;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.entity.effect.StatusEffectCategory;
import net.minecraft.entity.mob.HostileEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.particle.DustColorTransitionParticleEffect;
import net.minecraft.predicate.entity.EntityPredicates;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.Vec3f;
import stone926.mods.more_enchantments.MoreEnchantmentsMod;

public class MemorialCeremonyEffect extends StatusEffect {

  public MemorialCeremonyEffect() {
    super(StatusEffectCategory.BENEFICIAL, 0xc8fcfc);
  }

  @Override
  public boolean canApplyUpdateEffect(int duration, int amplifier) {
    return duration % 35 == 0;
  }

  @Override
  public void applyUpdateEffect(LivingEntity entity, int amplifier) {
    if (entity.getEntityWorld() instanceof ServerWorld server) {

      server
        .getEntitiesByClass(
          LivingEntity.class,
          Box.from(entity.getPos()).expand((1 + amplifier) * 35),
          EntityPredicates.VALID_LIVING_ENTITY
        ).stream()
        .forEach(l -> {
          l.heal((amplifier + 3) * 0.3F);
          if (l != entity || !l.hasStatusEffect(MoreEnchantmentsMod.MEMORIAL_CEREMONY_EFFECT))
            server.spawnParticles(
              new DustColorTransitionParticleEffect(
                new Vec3f(0.85F, 1, 1),
                new Vec3f(1, 1, 1),
                1.4F
              ),
              l.getX(), l.getY() + 1, l.getZ(),
              15,
              0.8, 0.8, 0.8,
              0.7
            );
        });


      server
        .getEntitiesByClass(
          LivingEntity.class,
          Box.from(entity.getPos()).expand(3),
          EntityPredicates.VALID_LIVING_ENTITY
        ).stream()
        .filter(l -> l.getAttacking() == entity || (entity instanceof PlayerEntity && l instanceof HostileEntity))
        .forEach(l -> {
          l.takeKnockback(amplifier + 2, entity.getX() - l.getX(), entity.getZ() - l.getZ());
        });
    }
  }

  @Override
  public void onApplied(LivingEntity entity, AttributeContainer attributes, int amplifier) {
    super.onApplied(entity, attributes, amplifier);
    applyUpdateEffect(entity, amplifier);
  }

  @Override
  public void onRemoved(LivingEntity entity, AttributeContainer attributes, int amplifier) {
    applyUpdateEffect(entity, Math.max(amplifier - 1, 0));
    super.onRemoved(entity, attributes, amplifier);
  }

}
